-- dispatch_task.lua
-- 此任务一直开着，外部可以不停地往这里下发任务
-- 一些任务会pending住


TRACE_ENABLE = true;
_DEBUG_MSG = true;

-- boot
require('scripts.boot')

-- common
require("common")
require('module')

-- objects
require('object.simple_class')
require('object.object')
require('object.hookable')
require('object.event_listener')

-- base module
require('module')
require('module_base.event_listener')
require('module_base.msg_listener')

-- common managers
require('manager.log_mgr')
require('manager.event_mgr')
require('manager.thread_mgr')
require('manager.file_mgr')
require('manager.task_mgr')

print('------------------ DISPATCH TASK -------------------------')

-- set zip if exists
if _G.ZIP_FILE and lfs.attributes(_G.ZIP_FILE) ~= nil then
    FILE_MGR.set_zip(_G.ZIP_FILE);
end

cur_dispatch_id = nil;
input_args = nil;
parent_task = arg[1];
local update_freq = arg[2];

-- 回信
function post_back(msg_id, msg_content)
    TASK_MGR.post_message(parent_task, msg_id, cur_dispatch_id, msg_content); 
end

-- 清空全局的arg
arg = nil;

-- 检查任务信箱的线程
local function _main_loop()
    local sleeptime = 1000 / update_freq;
    local last_time = os.clock();
    local cur_time;

    while true do
        
        local function _run()
            -- 接收消息
            local msg, flag, rc = task.receive(0);
            if rc == 0 then
                local data = table.fast_load(msg);
                local id = assert(data.id);
                cur_dispatch_id = id;
                input_args = data.params;
                local task_script = data.script;

                local status, func, err = pcall(loadfile, task_script);
                if not status or func == nil then
                    logger:error(string.format('Load dispatch task <%s> error: %s', task_script, err));
                else
                    local res, msg = xpcall(func, debug.traceback);
                    if not res then
                        logger:error(string.format('Run dispatch task <%s> error.\n', msg));
                    end
                end
            end
        end

        -- 确保在安全的情况下运行，以免task报错，把dispatch_task停下来
        local res, msg = xpcall(_run, debug.traceback);
        if not res then
            logger:error(msg);
        end

        -- sleep
        task.sleep(sleeptime);
    end
end

_main_loop();

